package com.zhaoguang.car.service.impl;

import com.zhaoguang.car.common.EncryptUtil;
import com.zhaoguang.car.common.RespBean;
import com.zhaoguang.car.entity.UserInfo;
import com.zhaoguang.car.manager.TokenManager;
import com.zhaoguang.car.mapper.UserLogRegMapper;
import com.zhaoguang.car.service.UserLogRegService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserLogRegServiceImpl implements UserLogRegService {

    @Autowired
    UserLogRegMapper userLogRegMapper;

    @Autowired
    TokenManager tokenManager;

    @Override
    public String registerUser(UserInfo user) {
        String str = EncryptUtil.getMD5Encrypt(user.getPassword());
        user.setPassword(str);

        int ok = userLogRegMapper.registerUser(user);
        if (ok == 1) {
            return "注册用户成功";
        }
        return "注册失败";
    }

    @Override
    public RespBean login(UserInfo user) {
        UserInfo userDB = userLogRegMapper.findUserByPhone(user.getPhone());
        if (userDB != null) {
            String phoneDB = userDB.getPhone();
            String passwordDB = userDB.getPassword();

            String phone = user.getPhone();
            String password = EncryptUtil.getMD5Encrypt(user.getPassword());

            if (phoneDB.equals(phone) && passwordDB.equals(password)) {
                //缓存token
                String token = tokenManager.createToken();
                boolean result = tokenManager.cacheToken(userDB.getUserId(), token);
                if (result) {
                    System.out.println("用户 " + userDB.getUsername() + " 缓存token成功");
                }

                UserInfo me = new UserInfo();
                me.setUserId(userDB.getUserId());
                me.setShopId(userDB.getShopId());
                me.setPhone(phoneDB);
                me.setUsername(userDB.getUsername());
                me.setToken(token);

                return RespBean.success("登录成功", me);
            }
        }
        return RespBean.error("账号不正确或密码错误");
    }


    @Override
    public RespBean logout(int userId) {
        boolean result = tokenManager.deleteToken(userId);
        if (result) {
            return RespBean.success("用户退出成功");
        }
        return RespBean.error("用户退出失败");
    }
}
